package com.irononetech.android.formcomponent.view;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.irononetech.android.Application.Application;
import com.irononetech.android.Webservice.URL;
import com.irononetech.android.fileio.FileOperations;
import com.irononetech.android.formcomponent.FormObject;
import com.irononetech.android.claimsone.R;
import com.irononetech.android.draftserializer.FormObjectDeserializer;
import com.irononetech.android.utilities.JPGFileFilter;

public class CustomGalleryJobImagesAdd extends Activity {
	Logger LOG = LoggerFactory.getLogger(FormObjectDeserializer.class);
	private int count;
	private boolean[] thumbnailsselection;
	private String[] arrPath;
	private ImageAdapter imageAdapter;
	FormObject formObject;
	/** Called when the activity is first created. */

	List<File> finalFileList;
	ArrayList<String> selectedFileList;
	ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			LOG.debug("ENTRY onCreate");
			setContentView(R.layout.imagegallerymain);
			formObject = Application.getFormObjectInstance();
			
			new SelectAsyncTask().execute();
			progressDialog = ProgressDialog.show(this, "",	"Loading...", true);

			final Button selectBtn = (Button) findViewById(R.id.selectBtn);
			selectBtn.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					LOG.debug("ENTRY ","selectBtn-onClick");
					final int len = thumbnailsselection.length;
					//int cnt = 0;
					String selectImages = "";
					for (int i =0; i<len; i++)
					{
						if (thumbnailsselection[i]){
							//cnt++;
							selectImages = selectImages + arrPath[i] + "|";
							selectedFileList.add(arrPath[i]);
						}
					}

					//SLIC Code
					String destinationFolder = formObject.getJobNo() + "";

					if(!destinationFolder.equals("")){
						FileOperations.copyFilesFromDirToDirAddImages(selectedFileList, destinationFolder + "/images");
						formObject.setselectedAccidentImages(thumbnailsselection);
					}
					/*else{
						new AlertDialog.Builder(CustomGalleryJobImagesAdd.this)
						.setTitle(R.string.alert_dialog_two_buttons_title)
						.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
							}
						})
						.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
							}
						})
						.create();
					}*/
					finish();
					LOG.debug("SUCCESS ", "selectBtn-onClick");
				}

			});

			Toast.makeText(this, "long click the thumbnails to view", Toast.LENGTH_LONG).show();
			LOG.debug("SUCCESS onCreate");
		} catch (Exception e) {
			LOG.error("onCreate:10452");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
			progressDialog.dismiss();
		}
	}

	private class SelectAsyncTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			try {
				super.onPostExecute(result);
				
				selectedFileList = new ArrayList<String>();
				count= finalFileList.size();
				int dd = count;
				arrPath = new String[count];
				thumbnailsselection = new boolean[count];
				boolean[] arr = formObject.getselectedAccidentImages();
				
				if (thumbnailsselection != null && arr != null) {
					for (int i = 0; i < thumbnailsselection.length; i++) {
						
						/* Need this condition on a situation where user select few images
						 * and then copy more images to Copied folder.
						 * Without this condition user gets an empty page with no images to select.
						 * */
						if(i < arr.length)
							thumbnailsselection[i] = arr[i];
						else
							break;
					}
				}
				
				for (int i = 0; i < count; i++) {
					arrPath[i]=finalFileList.get(i).toString();
				}
							
				
				GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
				imageAdapter = new ImageAdapter();
				imagegrid.setAdapter(imageAdapter);

				progressDialog.dismiss();
			} catch (Exception e) {
				LOG.error("onPostExecute:10450");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
				progressDialog.dismiss();
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				finalFileList= imageList();
			} catch (Exception e) {
				LOG.error("doInBackground:10451");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
			}
			return null;
		}
	}

	public class ImageAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ImageAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			//return count;
			return finalFileList.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(
						R.layout.galleryitem, null);
				holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
				holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

				convertView.setTag(holder);
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			final ViewHolder holder1 = holder;
			holder.checkbox.setId(position);
			holder.imageview.setId(position);
			holder.checkbox.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					CheckBox cb = (CheckBox) v;
					int id = cb.getId();
					if (thumbnailsselection[id]){
						cb.setChecked(false);
						thumbnailsselection[id] = false;
					} else {
						cb.setChecked(true);
						thumbnailsselection[id] = true;
					}
				}
			});
			holder.imageview.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					CheckBox cb = (CheckBox)holder1.checkbox;
					int id = cb.getId();
					if (thumbnailsselection[id]){
						cb.setChecked(false);
						thumbnailsselection[id] = false;
					} else {
						cb.setChecked(true);
						thumbnailsselection[id] = true;
					}
				}
			});
			holder.imageview.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					try {
						// Removed due to high memory consumption (3MB >
						// images will generate an exception)
						/*
						 * Intent mIntent = new
						 * Intent(CustomGalleryJobDocsAdd.this,
						 * PopupImage.class);
						 * mIntent.putExtra("selectedImage",
						 * arrPath[v.getId()]); startActivity(mIntent);
						 */
						Intent intent = new Intent();
						intent.setAction(Intent.ACTION_VIEW);
						intent.setDataAndType(Uri.parse("file://" + arrPath[v.getId()]), "image/*");
						startActivity(intent);
					} catch (Exception e) {
						LOG.error("onClick");
						   if(e != null){
							LOG.error("Message: " + e.getMessage());
							LOG.error("StackTrace: " + e.getStackTrace());
						  }
					}
					return false;
				}
			});
			
			Bitmap bitmapImage = FileOperations.ShrinkBitmap(finalFileList.get(position).toString(), 150, 200);

			BitmapDrawable drawableImage = new BitmapDrawable(bitmapImage );                
			holder.imageview.setImageDrawable(drawableImage);
			holder.checkbox.setChecked(thumbnailsselection[position]);
			holder.id = position;
			return convertView;
		}
	}

	public List<File> imageList(){

		//			File myDirectory = new File(Environment.getExternalStorageDirectory(), "mydirectory");
		//			if(!myDirectory.exists()) {
		//			    myDirectory.mkdirs();
		//			}
		//File a = Environment.getExternalStorageDirectory();
		File f = new File(URL.getSLIC_COPIED()); 
		List<File> fileList = FileOperations.listFiles(f, new JPGFileFilter(), true);

		//String fileNames = "";
		//for (int i = 0; i < fileList.size(); i++) {
		//fileNames += ">>" + fileList.get(i).getPath() + "\n";
		//}
		return fileList;
	}

	public void on_click_back_button(View v){
		finish();
	}
}

class ViewHolder {
	ImageView imageview;
	CheckBox checkbox;
	int id;
}